<template>
  <div style="display: none">
    <input id="upload_file" accept="image/*" type="file" multiple @change="fileChange($event)">
    <tool-tip ref="toolTips"/>
  </div>
</template>

<script>
import { PostUploadFile } from '@/api/fileUpload'
import toolTip from '@/components/toolTip'
export default {
  name: 'Index',
  components: {
    toolTip
  },
  data() {
    return {
      singleImg: []
    }
  },
  methods: {
    editAvatar() {
      document.getElementById('upload_file').click()
    },
    fileChange(el) {
      if (!el.target.files[0].size) return
      this.fileList(el.target)
      el.target.value = ''
    },
    fileList(fileList) {
      const files = fileList.files
      for (let i = 0; i < files.length; i++) {
        // 判断是否为文件夹
        if (files[i].type !== '') {
          this.fileAdd(files[i])
        } else {
          // 文件夹处理
          this.folders(fileList.items[i])
        }
      }
    },
    // 文件夹处理
    folders(files) {
      const _this = this
      // 判断是否为原生file
      if (files.kind) {
        files = files.webkitGetAsEntry()
      }
      files.createReader().readEntries(function(file) {
        for (let i = 0; i < file.length; i++) {
          if (file[i].isFile) {
            _this.foldersAdd(file[i])
          } else {
            _this.folders(file[i])
          }
        }
      })
    },
    foldersAdd(entry) {
      const _this = this
      entry.file(function(file) {
        _this.fileAdd(file)
      })
    },
    fileAdd(file) {
      if (this.limit !== undefined) this.limit--
      if (this.limit !== undefined && this.limit < 0) return
      // 总大小
      this.size = this.size + file.size
      // 判断是否为图片文件
      if (file.type.indexOf('image') === -1) {
        this.$dialog.toast({ mes: '请选择图片文件' })
      } else {
        const reader = new FileReader()
        const image = new Image()
        const _this = this
        reader.readAsDataURL(file)
        reader.onload = function() {
          file.src = this.result
          image.onload = function() {
            const width = image.width
            const height = image.height
            file.width = width
            file.height = height
            _this.singleImg = file
            // console.log(_this.singleImg)
          }
          // image.src = file.src
          _this.uploadFile(file)
        }
      }
    },
    uploadFile(file) {
      const formData = new FormData()
      formData.append('file', file)
      PostUploadFile(formData).then(res => {
        console.log(res)
        const data = res.data
        if (data.status_code === 200) {
          const singleImg = data.data.file
          this.$emit('singleImg', singleImg)
        } else {
          this.$refs.toolTips.showToolTips(data.message, 2000)
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
